<template>
    <div id="square" class="flex-1 flex-col relative overflow-hidden box-border pb-20px">
        <div
            class="h-64px w-full box-border py-10px px-30px flex items-center justify-between"
            style="border-bottom: solid 1px #e5e5e5"
        >
            <n-tabs v-model:value="visibleTo" @update:value="refresh()">
                <n-tab name="all" tab="看别人"></n-tab>
                <n-tab v-if="user.role === 0" name="mine" tab="看自己"></n-tab>
            </n-tabs>
            <Xicon
                name="ai"
                :size="36"
                class="cursor-pointer"
                @click="
                    () => {
                        emits('chat')
                    }
                "
            />
        </div>
        <div
            ref="scrollBoxRef"
            class="flex-1 flex-center overflow-scroll"
            style="scrollbar-width: none"
            @scroll="handleScroll"
        >
            <div class="w-60% h-full">
                <div v-if="moments.length === 0" class="h-full flex-center">
                    <n-result status="418" title="广场上空空如也">
                        <template #footer v-if="user.role === 0">
                            <n-button :focusable="false" @click="createMomentFormVisable = true">
                                去给别人瞧瞧
                            </n-button>
                        </template>
                    </n-result>
                </div>
                <div v-else class="w-full flex-col gap-20px box-border py-20px">
                    <MomentItem
                        v-for="moment in moments"
                        :key="moment.id"
                        :moment="moment"
                        :visible-to="visibleTo"
                        @like="handleLike"
                        @delete="handleDelete"
                    />
                    <div class="w-full flex-center my-10px font-size-0.7rem opacity-70">
                        没有更多了
                    </div>
                </div>
            </div>
            <div class="absolute right-30px bottom-30px flex-col gap-10px">
                <n-button round class="w-48px h-48px p-0" :focusable="false" @click="refresh()">
                    <Xicon name="refresh" />
                </n-button>
                <n-button
                    v-if="user.role === 0"
                    round
                    class="w-48px h-48px p-0"
                    :focusable="false"
                    @click="createMomentFormVisable = true"
                >
                    <Xicon name="moment" />
                </n-button>
                <n-button
                    round
                    class="w-48px h-48px p-0 duration-300 ease"
                    :focusable="false"
                    @click="scrollToTop"
                    :style="{
                        transform: scrollToTopButtonVisable ? 'scale(1)' : 'scale(0)',
                    }"
                >
                    <Xicon name="toTop" />
                </n-button>
            </div>
        </div>
        <n-drawer
            v-model:show="createMomentFormVisable"
            :width="500"
            :trap-focus="false"
            :block-scroll="false"
            placement="right"
            to="#square"
        >
            <n-drawer-content title="发表动态">
                <MomentForm v-if="createMomentFormVisable" @publish="handlePublic" />
            </n-drawer-content>
        </n-drawer>
    </div>
</template>

<script lang="ts" setup>
import { ref, onActivated } from 'vue'
import { useRouter } from 'vue-router'
import type { MomentDto, MomentVo } from '@/service/types/moment'

import { getMoments, createMoment, deleteMoment, likeMoment } from '@/service/api/moment'

import Xicon from '@/components/xicon/index.vue'
import MomentItem from '@/components/moment-item/index.vue'
import MomentForm from '@/components/moment-form/index.vue'

const emits = defineEmits<{
    chat: [void]
}>()

const user = JSON.parse(localStorage.getItem('user') || '{}')

const visibleTo = ref<'mine' | 'all'>('all')

const createMomentFormVisable = ref(false)
const moments = ref<MomentVo[]>([])

const scrollToTopButtonVisable = ref(false)
const scrollBoxRef = ref<HTMLDivElement>()

onActivated(async () => {
    await refresh()
})

const refresh = async () => {
    try {
        moments.value = await getMoments({
            userId: user.id,
            page: 1,
            size: 10,
            type: visibleTo.value === 'mine' ? 1 : 0,
        })
    } catch (err: any) {
        window.NMessage.error(err.msg)
    }
}

const handleScroll = (e: any) => {
    const top = e.target.scrollTop

    if (top >= 100) {
        scrollToTopButtonVisable.value = true
    } else {
        scrollToTopButtonVisable.value = false
    }
}

const scrollToTop = () => {
    if (scrollBoxRef.value) {
        scrollBoxRef.value.scrollTo({ top: 0, behavior: 'smooth' })
    }
}

const handlePublic = async (dto: MomentDto) => {
    try {
        await createMoment(dto)
        await refresh()
        createMomentFormVisable.value = false
        window.NMessage.success('发表成功')
    } catch (err: any) {
        window.NMessage.error(err.msg)
    }
}

const handleDelete = async (id: string) => {
    try {
        await deleteMoment(id)
        await refresh()
        window.NMessage.success('删除成功')
    } catch (err: any) {
        window.NMessage.error(err.msg)
    }
}

const handleLike = async (id: string) => {
    try {
        const res = await likeMoment(id)
        moments.value.find((item) => item.id === id)!.likeCount = res.likeCount
    } catch (err: any) {
        window.NMessage.error(err.msg)
    }
}

const setMoments = (data: MomentVo[]) => {
    moments.value = data
}

defineExpose({
    setMoments,
})
</script>

<style scoped></style>
